package com.finger.gulimall.product.filter;

import com.finger.common.constant.AuthConstant;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

public class LoginFilter implements Filter {


    private HashSet<String> excludedUris;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String param = filterConfig.getInitParameter("excludedUris");
        if (StringUtils.isNotBlank(param)) {
            List<String> strings = Arrays.asList(param.split(","));
            this.excludedUris = new HashSet<String>(strings);
        }

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) servletRequest;

        if(excludedUris.contains(req.getRequestURI())){
            // 去除过滤路径
            filterChain.doFilter(req,servletResponse);

        }else{
            HttpSession session = req.getSession();
            HttpServletResponse resp = (HttpServletResponse) servletResponse;
            Object loginMember = session.getAttribute(AuthConstant.LOGIN_MEMBER);
            if(loginMember==null){
                // 用户没有登录
                resp.sendRedirect("http://auth.gulimall.com/login.html");
            }
            // 用户登录成功
            filterChain.doFilter(req,resp);
        }

    }
}
